package com.hwz.gulimall.ware.service.impl;

import com.hwz.common.utils.R;
import com.hwz.gulimall.ware.dao.WareSkuDao;
import com.hwz.gulimall.ware.entity.WareSkuEntity;
import com.hwz.gulimall.ware.feign.FeignSkuInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwz.common.utils.PageUtils;
import com.hwz.common.utils.Query;

import com.hwz.gulimall.ware.dao.WareInfoDao;
import com.hwz.gulimall.ware.entity.WareInfoEntity;
import com.hwz.gulimall.ware.service.WareInfoService;
import org.springframework.util.StringUtils;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    FeignSkuInfoService feignSkuInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareInfoEntity> wareInfoEntityQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(params.get("key")) ){
            wareInfoEntityQueryWrapper.and(obj -> obj.eq("id", params.get("key")).or()
                    .like("name", params.get("key")).or()
                    .like("address", params.get("key")).or()
                    .like("areacode", params.get("key")));
        }


        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                wareInfoEntityQueryWrapper
        );


        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {

        //1、查询库存情况
        WareSkuEntity baseWareSkuEntity = wareSkuDao.selectOne(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));

        //如果库存为0新增一条记录
        if (baseWareSkuEntity == null || baseWareSkuEntity.getStock() == 0){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);

            //获取skuName
            try {
                R info = feignSkuInfoService.info(skuId);
                if (info.getCode() == 0){
                    Map<String,Object> data = (Map<String,Object> )info.get("skuInfo");
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            wareSkuDao.insert(wareSkuEntity);
            return;
        }

        wareSkuDao.addStack(skuId, wareId, skuNum);


    }

}